﻿using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using extend_360.dto;
using extend_360.utils;

namespace extend_360
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Program===Starting");
            string appPath = SystemUtils.GetDomainPath() + "/config/config.json";
            Config config = FileUtils.ReadFile<Config>(appPath);

            string ratio = string.Empty;
            SetRatio(config.Ratio, ref ratio);

            VPN(config.VpnConfg);

            ActionUtils.InstallPackage(config, ratio);

            Console.WriteLine("Program===End");
        }

        static string RegistryRatio = @"SOFTWARE\John\Ratio";

        /// <summary>
        /// 设置分辨率
        /// </summary>
        /// <param name="ratios"></param>
        /// <param name="ratio">当前系统的分辨值</param>
        static void SetRatio(string[] ratios, ref string ratio)
        {
            if (ratios == null)
                throw new Exception("未配置分辨率信息");

            ratio = ratios[(new Random().Next(0, ratios.Length))].Trim();
            const string ratioKey = "RatioConfig";

            if (!RegistryKeyUtils.CheckRegistryExists(RegistryRatio, ratioKey))
            {
                ratio = RegistryKeyUtils.GetRegistryValue(RegistryRatio, ratioKey, ratio);

                SystemUtils.ConsoleWrite("第一次安装等待50秒", ConsoleColor.Yellow);
                Thread.Sleep(50);
            }

            SystemUtils.ConsoleWrite("设置分辩率：" + ratio, ConsoleColor.Green);
            string[] arrRatio = ratio.Split("*");
            WindowsAPIUtils.SetResolution(int.Parse(arrRatio[0]), int.Parse(arrRatio[1]));
        }


        static string RegistryVPNConfig = @"SOFTWARE\John\VPN";

        static void VPN(List<Config.VPN> vpns)
        {
            if (vpns == null || vpns.Count == 0)
                throw new Exception("VPN配置文件为空");

            // 使用固定VPN
            string vpnConfigStr = JsonSerializer.Serialize(vpns[new Random().Next(0, vpns.Count)]);
            vpnConfigStr =
                RegistryKeyUtils.GetRegistryValue(RegistryVPNConfig, "VPNConfig", vpnConfigStr);
            Config.VPN vpnConfg = JsonSerializer.Deserialize<Config.VPN>(vpnConfigStr);

            SystemUtils.ConsoleWrite("VPN===Connection", ConsoleColor.Magenta);
            Console.WriteLine("VPN===Connection");
            VPNConnectionUtils.Connect(vpnConfg.Name, vpnConfg.Address,
                vpnConfg.User,
                vpnConfg.Pwd);
            SystemUtils.ConsoleWrite("VPN===Connection Finish", ConsoleColor.Magenta);
        }
    }
}